//
//  MobileInvitationViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-5-28.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "MobileInvitationViewController.h"
#import "Config.h"
#import "Helper.h"
#import "DBKit.h"
#import "Contact.h"
#import "JMFBase.h"
#import <MessageUI/MessageUI.h>
#import "InvitationMessageViewController.h"

//  -业务逻辑细节说明-
//
//  @abstract       viewWillAppear时，VC会查询数据库，查询到指定圈子下的准备邀请的好友信息，赋值给姓名数据源和手机号码数据源，reload tableview显示在列表中。此时会根据列表是否为空来决定“添加“按钮的显示，如果列表数据为空，那么按钮显示”添加“；如果列表不为空，那么按钮要显示”继续添加“。
//                  用户输入了姓名和手机号码后点击“添加”按钮，VC会将数据存入数据库（对应的数据表是以手机号码和circleId为联合主键，所以在当前圈子下手机号码不能重复），并且调用obtainAndReloadDataSource方法，来获取数据源并且刷新tableview，响应用户的修改。
//                  点击“删除”按钮后，VC会将此好友的信息从数据库中删除，并且调用obtainAndReloadDataSource方法，来获取数据源并且刷新tableview，响应用户的修改。
//                  点击邀请按钮时，VC会将手机号码数据源传给短信发送组件。
//                  短信发送成功后，VC会将姓名数据源和手机号码数据源分别转化为以指定符号隔开的字符串，用于作为向服务器发送添加圈子成员请求时的参数。同时变量_dismissWhenDidApprear会被设为YES，那么在viewDidAppear时，此VC会被自动的dismiss，回到邀请选项页面。
//                  
//

//  @discussion
//
//

//  @notes          obtainAndReloadDataSource方法较为重要，它完成了VC与数据层的数据交换，并且会更新按钮或者tableview的显示。用户添加或者删除一个好友都会访问数据库，并且操作后，都要在tableview表现出来。


//  -类修改日志-
//  修改人   修改时间        针对版本   修改描述

//  周益     2013-05-30    1.0.0     当用户没有添加准备邀请中的好友时，点击“邀请按钮”时，如果输入框里的好友信息满足要求，那么此好友能够直接被邀请，不需要先添加到列表中，再邀请。

@interface MobileInvitationViewController ()

@end

@implementation MobileInvitationViewController
{
    NSMutableArray *_contactsArray;
    
    BOOL _status;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = _L(@"vc_title_107");
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *inviteButton = [Helper buttonWithStyle:ButtonStyleNavigationInvite];
    [inviteButton addTarget:self action:@selector(inviteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:inviteButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    //姓名输入VIEW
    UIView *nameView = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 301.0f, 45.0f)];
    nameView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_010@2x" ofType:@"png"]]];
    [self.view addSubview:nameView];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 10.0f, 30.0f, 25.0f)];
    nameLabel.text = _L(@"title_43");
    nameLabel.font = _SYS_FONT_003;
    [nameView addSubview:nameLabel];
    
    _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(80.0f, 0.0f, 200.0f, 45.0f)];
    _nameTextField.returnKeyType = UIReturnKeyDone;
    _nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTextField.font = _SYS_FONT_003;
//    [_nameTextField becomeFirstResponder];
    _nameTextField.delegate = self;
    _nameTextField.placeholder = _L(@"holder_29");
    [nameView addSubview:_nameTextField];
    
    
    //手机号码输入VIEW
    UIView *mobileView = [[UIView alloc] initWithFrame:CGRectMake(10.0f, nameView.frame.origin.y + nameView.frame.size.height + 5.0f, 301.0f, 45.0f)];
    mobileView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_010@2x" ofType:@"png"]]];
    [self.view addSubview:mobileView];
    
    UILabel *mobileLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 10.0f, 60.0f, 25.0f)];
    mobileLabel.text = _L(@"title_69");
    mobileLabel.font = _SYS_FONT_003;
    [mobileView addSubview:mobileLabel];
    
    _mobileTextField = [[UITextField alloc] initWithFrame:CGRectMake(80.0f, 0.0f, 200.0f, 45.0f)];
    _mobileTextField.returnKeyType = UIReturnKeyDone;
    _mobileTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _mobileTextField.keyboardType = UIKeyboardTypePhonePad;
    _mobileTextField.font = _SYS_FONT_003;
    _mobileTextField.delegate = self;
    _mobileTextField.placeholder = _L(@"holder_16");
    [mobileView addSubview:_mobileTextField];
    
    //添加按钮
    _addButton = [[UIButton alloc] initWithFrame:CGRectMake(10, mobileView.frame.origin.y + mobileView.frame.size.height + 10.0f, 300, 44)];
    [_addButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    [_addButton setTitle:_L(@"btn_add_01") forState:UIControlStateNormal];
    [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _addButton.titleLabel.font = _SYS_FONT_007;
    [_addButton addTarget:self action:@selector(addButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addButton];
    
    
    _friendsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, _addButton.frame.origin.y + _addButton.frame.size.height + 15.0f, 320.0f, 6*44.0f + 50.0f)];
    _friendsTableView.delegate = self;
    _friendsTableView.dataSource = self;
    [self.view addSubview:_friendsTableView];
    
    UIView *headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 320, 30)];
    _friendsTableView.tableHeaderView = headerView;
    headerView.backgroundColor = [UIColor colorWithRed:173.0f/255.0f green:173.0f/255.0f blue:173.0f/255.0f alpha:1.0f];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 200.0f, 30.0f)];
    titleLabel.text = _L(@"title_70");
    titleLabel.textColor = [UIColor colorWithRed:242.0f/255.0f green:242.0f/255.0f blue:242.0f/255.0f alpha:1.0f];
    titleLabel.font = _SYS_FONT_002;
    titleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:titleLabel];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self obtainAndReloadDataSource];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_dismissWhenDidApprear) {
        
        [self dismissModalViewControllerAnimated:false];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    _contactsArray = nil;
}


#pragma mark - 返回按钮流程
/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    if (_mobileTextField.text.length > 0 || _nameTextField.text.length > 0) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_87") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else {
    
        [self.navigationController popViewControllerAnimated:true];
    }
}


//////////////////////////

#pragma mark - 自定义事件
/*!
 @abstract 邀请按钮事件
 */
- (void)inviteButtonEvent:(id)sender
{

    _contactsArray = [[DBKit sharedDBKit] transformToContactInfo];
    
    //当列表为空的时候，只需要判断姓名textfield和手机号码textfield是否为空，并且都为空的情况。（以为3种情况提示语不同）
    //列表不为空的时候，只要求邀请列表中的好友
    if (_contactsArray.count == 0) {
        
        if (_nameTextField.text.length == 0 && _mobileTextField.text.length == 0) {
            
            [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_55")];
            return;
        }
        
        if (_nameTextField.text.length == 0) {
            [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_29")];
            return;
        }
        
        if (_mobileTextField.text.length == 0) {
            [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_16")];
            return;
        }
        
        if (_nameTextField.text.length != 0 && _mobileTextField.text.length != 0) {
            
            if (![Helper validateMobile:_mobileTextField.text]) {
                [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_39")];
                return;
            }
            
            if (![self friendCheck]) {
                return;
            }
            
            [self moveFriendIntoTableView];
        }
    }
    
    InvitationMessageViewController* picker = [[InvitationMessageViewController alloc] init];
    picker.contactsToInvite = _contactsArray;
    [self.navigationController pushViewController:picker animated:true];
    
}

/*!
 @abstract 添加按钮事件，将新增的好友添加到数据库中，并且马上刷新tableview
 */
- (void)addButtonEvent:(id)sender
{
    if (_nameTextField.text.length == 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_29")];
        return ;
    }
    
    if (_mobileTextField.text.length == 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_16")];
        return;
    }
    
    //验证手机号是否合法
    if (_mobileTextField.text.length != 0 && ![Helper validateMobile:_mobileTextField.text]) {
        
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_39")];
        return;
    }
    
    if (_nameTextField.text != nil && ![@"" isEqualToString:_nameTextField.text] && _mobileTextField.text != nil && ![@"" isEqualToString:_mobileTextField.text]) {
        
        //如果还不是好友关系
        if ([self friendCheck]) {
            
            [self moveFriendIntoTableView];
        }
    }
    
    [_nameTextField resignFirstResponder];
    [_mobileTextField resignFirstResponder];
}

/*!
 @abstract 删除按钮事件，删除数据库中的对应记录，并且马上刷新tableview
 */
- (void)deleteButtonEvent:(id)sender
{
    UIButton *clickButton = (UIButton *)sender;
    
    //clickButton.tag记录了用户点击的tableview的row
    NSString *mobile = [[_contactsArray objectAtIndex:clickButton.tag] mobile];
    
    if (mobile != nil) {
        
        DBKit *dbkit = [DBKit sharedDBKit];
        
        Contact *contact = [Contact new];
        contact.mobile = mobile;
        
        //删除数据库中的记录
        [dbkit remove:contact];
        
        [self obtainAndReloadDataSource];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameTextField resignFirstResponder];
    [_mobileTextField resignFirstResponder];
}


#pragma mark - 私有方法

- (BOOL)friendCheck
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_CHECK];
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    [request setValue:_mobileTextField.text forParameter:@"mobile"];
    NSDictionary *dict = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        _status = [jmf boolValue:@"data"];
        
        return YES;
    }
    else {
        [Helper easyShowJMFStatus:jmf];
        return NO;
    }
}
/*!
 @abstract 获取数据库中准备邀请的好友的记录，并且刷新tableview，根据记录是否为空，判断“添加”按钮title的显示。
 */
- (void)obtainAndReloadDataSource
{
    //从数据库里中获取当前准备邀请的好友
    _contactsArray = [[DBKit sharedDBKit] transformToContactInfo];
    
    [_friendsTableView reloadData];
    
    if (_contactsArray.count != 0) {
        
        [_addButton setTitle:_L(@"btn_add_02") forState:UIControlStateNormal];      //继续添加
    }else{
        [_addButton setTitle:_L(@"btn_add_01") forState:UIControlStateNormal];      //添加
    }
}

//将数据框中的好友数据填充到准备邀请中的人的列表中去
- (void)moveFriendIntoTableView
{
    Contact *contact = [Contact new];
    contact.name = _nameTextField.text;
    contact.mobile = _mobileTextField.text;
    contact.status = _status;
    
    //保存这一次的好友信息到数据库
    if ([[DBKit sharedDBKit] save:contact]) {
        
        [self obtainAndReloadDataSource];
        
        //重置textfield
        _nameTextField.text = @"";
        _mobileTextField.text = @"";
        
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _contactsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        //
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 90.0f, 25.0f)];
        nameLabel.font = _SYS_FONT_003;
        [cell.contentView addSubview:nameLabel];
        
        UILabel *mobileLabel = [[UILabel alloc] initWithFrame:CGRectMake(nameLabel.frame.origin.x + nameLabel.frame.size.width + 10.0f, 10.0f, 100.0f, 25.0f)];
        mobileLabel.font = _SYS_FONT_003;
        [cell.contentView addSubview:mobileLabel];
        
        
        //邀请按钮
        UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(mobileLabel.frame.origin.x + mobileLabel.frame.size.width + 50.0f, 10.0f, 46.5f, 22.5f)];
        [deleteButton setImage:[UIImage imageNamed:@"dynamic_btn_002_n"] forState:UIControlStateNormal];
        [deleteButton addTarget:self action:@selector(deleteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:deleteButton];
    }
    
    NSArray *subviews = [cell.contentView subviews];
    
    UILabel *nameLabel = [subviews objectAtIndex:0];
    UILabel *mobileLabel = [subviews objectAtIndex:1];
    UIButton *deleteButton = [subviews objectAtIndex:2];
    
    if (_contactsArray != nil && _contactsArray.count != 0) {
    
        deleteButton.tag = indexPath.row;
        
        nameLabel.text = [[_contactsArray objectAtIndex:indexPath.row] name];
        
        mobileLabel.text = [[_contactsArray objectAtIndex:indexPath.row] mobile];
    }
    else
    {
        NSLog(@"获取数据错误");
    }
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
